﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Newtonsoft.Json.Linq;
using System.IO;
using Ax.Tools;
using System.ComponentModel.Design;
using System.Drawing.Drawing2D;

namespace TipsForm
{
    public partial class economicControl : UserControl
    {
        public int ScrollWidth = 8;
        public Color ScrollColor = Color.FromArgb(160, 160, 160);
        public Color ScrollHoverColor = Color.FromArgb(200, 200, 200);

        Rectangle scrollRect;
        const int invalidIndex = -2;
        Pen m_dottedPen = new Pen(Color.FromArgb(80, 0, 0), 1);
        int hoverIndex = invalidIndex;
        int selectIndex = invalidIndex;
        int scrollStartHeight;
        int lastScrollStartHeight;
        bool leftBtnDown;
        bool scrollHovered;
        int lastHeight;
        bool showScroll = true;
        string kxStr;
        string cjStr;
        EconomicNews news;
        //EconomicCalendar calendar;
        List<EconomicCalendar> calendars = new List<EconomicCalendar>();
        bool isNews;

        public bool IsDesignMode()
        {
            return GetService(typeof(IDesignerHost)) != null || System.ComponentModel.LicenseManager.UsageMode == System.ComponentModel.LicenseUsageMode.Designtime;
        }

        public economicControl()
        {
            InitializeComponent();
            if (!IsDesignMode())
            {
                string kxStr = File.ReadAllText(Application.StartupPath + "/kx.txt");
                string cjStr = File.ReadAllText(Application.StartupPath + "/cj.txt");
                isNews = false;
                news = new EconomicNews();
                for (int i = 0; i < 3; i++)
                {
                    var job = JObject.Parse(cjStr);
                    var ca = new EconomicCalendar();
                    ca.Time = DateTime.Parse(job["time"].ToString());
                    ca.Title = job["title"].ToString();
                    ca.Importance = job["importance"].ToString();
                    ca.Before = job["before"].ToString();
                    ca.Forecast = job["forecast"].ToString();
                    ca.Reality = job["reality"].ToString();
                    ca.Effect = job["effect"].ToString();
                    ca.State = job["state"].ToString();
                    calendars.Add(ca);
                }
                //var job = JObject.Parse(kxStr);
                //news.Time = DateTime.Parse(job["time"].ToString());
                //news.Title = job["title"].ToString();
                //news.Importance = job["importance"].ToString();
            }
            SetStyle(ControlStyles.UserPaint | ControlStyles.AllPaintingInWmPaint | ControlStyles.OptimizedDoubleBuffer, true);
        }

        protected override void OnPaint(PaintEventArgs e)
        {
            base.OnPaint(e);
            var g = e.Graphics;
            Font font = new Font("微软雅黑", 10);
            if (isNews)
            {
                DrawNews(g, font);
            }
            else
            {
                DrawCalendars(g, font);
            }
            DrawScroll(g);

            Pen pen = new Pen(Color.FromArgb(221, 221, 221));
            pen.DashStyle = DashStyle.Dash;
            e.Graphics.DrawLine(pen, 0, Height - 1, Width, Height - 1);
        }

        private void DrawNews(Graphics g, Font font)
        {
            Color txtColor = news.Importance == "高" ? Color.Red : Color.Black;
            //画时间
            g.DrawString(news.Time.ToString("HH:mm"), font, new SolidBrush(Color.FromArgb(80, 162, 229)), 12, 37);
            //画内容
            g.DrawString(news.Title, font, new SolidBrush(txtColor), new RectangleF(57, 37, 260, 135));
        }
        int itemHeight = 72;

        private void DrawCalendars(Graphics g, Font font)
        {
            for (int i = 0; i < calendars.Count; i++)
            {
                var calendar = calendars[i];
                Color txtColor = calendar.Importance == "高" ? Color.Red : Color.Black;
                var sb = new StringBuilder(calendar.Title + Environment.NewLine);
                sb.Append("前值 : ");
                sb.Append(calendar.Before);
                sb.Append("  预期 : ");
                sb.Append(calendar.Forecast);
                sb.Append("  实际 : ");
                sb.Append(calendar.Reality);
                sb.Append(Environment.NewLine);
                //画时间
                g.DrawString(calendar.Time.ToString("HH:mm"), new Font("微软雅黑", 9), new SolidBrush(Color.FromArgb(80, 162, 229)), 10, 7 + itemHeight * i + scrollStartHeight);
                //画国旗
                var key = Helper.GetSpellCode(calendar.State).ToLower() + ".png";
                if (!stateImages.Images.ContainsKey(key))
                    key = "other.png";
                g.DrawImage(stateImages.Images[key], 9, 30 + itemHeight * i + scrollStartHeight);
                //画内容
                g.DrawString(i + " " + sb.ToString(), font, new SolidBrush(txtColor), new RectangleF(57, 7 + itemHeight * i + scrollStartHeight, 260, 35));
                //画重要性和影响
                g.DrawImage(importImages.Images[calendar.Importance], 57, 48 + itemHeight * i + scrollStartHeight);
                //画三角
                //勾线
                //写字
                var position = new Point(102, 48 + itemHeight * i + scrollStartHeight);
                if (calendar.Effect == "||")
                {
                    var color = Color.FromArgb(253, 149, 37);
                    var str = "影响较小";
                    var size = g.MeasureString(str, font);
                    var rect = new Rectangle(position.X, position.Y, (int)size.Width + 20, (int)size.Height + 6);
                    var format = new StringFormat() { LineAlignment = StringAlignment.Center, Alignment = StringAlignment.Center };
                    g.DrawString(str, font, new SolidBrush(color), rect, format);
                    g.DrawRectangle(new Pen(color), rect);
                }
                else
                {
                    var strs = calendar.Effect.Split('|');
                    var liduo = strs[0];
                    if (liduo != "")
                    {
                        var color = Color.Red;
                        var size = g.MeasureString(liduo, font);
                        var rect = new Rectangle(position.X, position.Y, (int)size.Width + 20, (int)size.Height + 6);
                        var format = new StringFormat() { LineAlignment = StringAlignment.Center, Alignment = StringAlignment.Center };
                        g.DrawString(liduo, font, new SolidBrush(color), rect, format);
                        g.DrawRectangle(new Pen(color), rect);
                    }
                    var likong = strs[1];
                }
            }
        }
        int colHeight = 2, rowHeight = 75;

        #region 鼠标事件(控制滚动条)
        /// <summary>
        /// 绘制滚动条
        /// </summary>
        /// <param name="g"></param>
        private void DrawScroll(Graphics g)
        {
            g.SmoothingMode = SmoothingMode.AntiAlias;
            try
            {
                int scrollHeight = Math.Max(ScrollWidth, (int)((Height - colHeight) / ((float)calendars.Count) / rowHeight * (Height - colHeight)));
                if (scrollHeight < Height - colHeight)
                {
                    int startH = -(int)(scrollStartHeight / (float)(calendars.Count) / rowHeight * (Height - colHeight)) + colHeight;
                    if (showScroll)
                    {
                        scrollRect = new Rectangle(Width - ScrollWidth - 1, startH, ScrollWidth, scrollHeight);
                        PathHelper.FillRoundRectangle(g, new SolidBrush(scrollHovered ? ScrollHoverColor : ScrollColor), scrollRect, ScrollWidth / 2);
                    }
                }
            }
            catch (Exception ex)
            {
            	
            }
        }

        /// <summary>
        /// 限定滚动条范围
        /// </summary>
        private void CheckScrollHeight()
        {
            if (scrollStartHeight > 0)
                scrollStartHeight = 0;
            int h = Height - (calendars.Count) * rowHeight;
            if (scrollStartHeight <= h)
                scrollStartHeight = h;
        }

        protected override void OnMouseMove(MouseEventArgs e)
        {
            base.OnMouseMove(e);
            //m_hoverIndex = GetRowIndex(e);
            scrollHovered = leftBtnDown ? scrollHovered : scrollRect.Contains(e.Location);
            if (leftBtnDown && scrollHovered)
            {
                int x = (int)((e.Y - lastHeight) / (float)(Height - colHeight) * rowHeight * calendars.Count);
                scrollStartHeight = lastScrollStartHeight - x / rowHeight * rowHeight;
                CheckScrollHeight();
            }
            Invalidate();
        }

        protected override void OnMouseWheel(MouseEventArgs e)
        {
            base.OnMouseWheel(e);
            if (calendars.Count * itemHeight < Height - colHeight)
                return;
            if (showScroll)
            {
                scrollStartHeight += rowHeight * e.Delta / 240;
                CheckScrollHeight();
                Invalidate();
            }
        }

        protected override void OnMouseUp(MouseEventArgs e)
        {
            base.OnMouseUp(e);
            leftBtnDown = false;
            //selectIndex = GetRowIndex(e);
            Invalidate();
        }

        protected override void OnMouseDown(MouseEventArgs e)
        {
            base.OnMouseDown(e);
            leftBtnDown = true;
            if (scrollRect.Contains(e.Location))
            {
                lastHeight = e.Y;
                lastScrollStartHeight = scrollStartHeight;
                scrollHovered = true;
            }
        }
        #endregion
    }
}
